import axios from 'axios'

// 会话管理工具类
class SessionManager {
  constructor() {
    this.baseURL = 'http://127.0.0.1:8000'
  }

  // 创建会话
  async createSession(userId) {
    try {
      const response = await axios.post(`${this.baseURL}/user/create_session/`, {
        userid: userId
      })
      
      if (response.data.code === 200) {
        return {
          success: true,
          sessionId: response.data.session_id
        }
      } else {
        return {
          success: false,
          error: response.data.msg || '创建会话失败'
        }
      }
    } catch (error) {
      console.error('创建会话请求失败:', error)
      return {
        success: false,
        error: '网络错误，请重试'
      }
    }
  }

  // 验证会话
  async validateSession(sessionId) {
    try {
      const response = await axios.post(`${this.baseURL}/user/validate_session/`, {
        session_id: sessionId
      })
      
      if (response.data.code === 200) {
        return {
          success: true,
          userData: response.data.user_data
        }
      } else {
        return {
          success: false,
          error: response.data.msg || '会话验证失败'
        }
      }
    } catch (error) {
      console.error('会话验证请求失败:', error)
      return {
        success: false,
        error: '网络错误，请重试'
      }
    }
  }

  // 销毁会话
  async destroySession(sessionId) {
    try {
      const response = await axios.post(`${this.baseURL}/user/destroy_session/`, {
        session_id: sessionId
      })
      
      return response.data.code === 200
    } catch (error) {
      console.error('销毁会话失败:', error)
      return false
    }
  }

  // 检查用户是否已登录
  isLoggedIn() {
    return !!localStorage.getItem('userid') && !!localStorage.getItem('access_token')
  }

  // 获取当前用户ID
  getCurrentUserId() {
    return localStorage.getItem('userid')
  }

  // 获取访问令牌
  getAccessToken() {
    return localStorage.getItem('access_token')
  }

  // 清除本地存储的用户信息
  clearUserData() {
    localStorage.removeItem('token')
    localStorage.removeItem('retoken')
    localStorage.removeItem('userid')
    localStorage.removeItem('access_token')
  }

  // 更新本地存储的用户信息
  updateUserData(userData) {
    if (userData.token) localStorage.setItem('token', userData.token)
    if (userData.retoken) localStorage.setItem('retoken', userData.retoken)
    if (userData.userid) localStorage.setItem('userid', userData.userid)
    if (userData.access_token) localStorage.setItem('access_token', userData.access_token)
  }
}

// 创建单例实例
const sessionManager = new SessionManager()

export default sessionManager 